package com.example.demo.config;

import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Objects;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;



    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return Objects.equals(charSequence.toString(), s);
            }
        };
    }


    //配置忽略掉的 URL 地址,一般用于js,css,图片等静态资源
    @Override
    public void configure(WebSecurity web) throws Exception {
        //web.ignoring() 用来配置忽略掉的 URL 地址，一般用于静态文件
        web.ignoring().antMatchers("/js/**", "/css/**", "/fonts/**", "/images/**", "/lib/**");
    }

    // (认证)配置用户及其对应的角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    //    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().withUser("懒洋洋").password("123").roles("vip0")
//                .and()
//                .withUser("灰太狼").password("123").roles("vip1")
//                .and()
//                .withUser("喜羊羊").password("123").roles("vip2")
//                .and()
//                .withUser("小灰灰").password("123").roles("vip3")
//                .and()
//                .withUser("root").password("123").roles("vip1", "vip2", "vip3","vip0");
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests().

        http.authorizeRequests().antMatchers("/css/**", "/js/**", "/images/**").permitAll();
        //开启运行iframe嵌套页面
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .antMatchers("/","/login.html").permitAll();

        //身份验证
//        http.authorizeRequests()
//                .anyRequest().authenticated();//任何请求都必须经过身份验证
//        http.anyRequest().authenticated();
//        http.authorizeRequests().anyRequest().permitAll();

//
//        http.oauth2ResourceServer().jwt();

        http.authorizeRequests()
                .antMatchers("/level1/button").hasRole("vip0")
                .antMatchers("/level2/test").hasRole("vip1")
                .antMatchers("/level3/try").hasRole("vip2");

        http
                .authorizeRequests()
                //访问"/"和"/home"路径的请求都允许
//                .antMatchers("/", "/home","/staff","/staff/*")
//                .permitAll()
                //而其他的请求都需要认证
                .anyRequest()
                .authenticated()
                .and()
                //修改Spring Security默认的登陆界面
                .formLogin()
                .loginPage("/login")
                .usernameParameter("username")//自定义表单的用户名的name,默认为username
                .passwordParameter("password")//自定义表单的密码的name,默认为password
                .loginProcessingUrl("/dologin")//表单请求的地址，一般与form的action属性一致，注意：不用自己写doLogin接口，只要与form的action属性一致即可
                .defaultSuccessUrl("/index")//登录成功后跳转的页面（重定向）
                .failureForwardUrl("/test")//登录失败后跳转的页面（重定向）
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl("/login")
                .logoutUrl("/logout")
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .permitAll()
                .and().csrf().disable();


        //开启记住我功能,cookie接收，默认保存两周，自定义接收其前端
        http.rememberMe().rememberMeParameter("remember");



//        http.formLogin()
//                .and()
//                .formLogin()
//                .loginPage("/login")
//                .usernameParameter("username")
//                .passwordParameter("password")
//                .loginProcessingUrl("/doLogin")
//                .successForwardUrl("/index")
//                .failureForwardUrl("/toLogin")
//                .and()
//                .logout()
//                .logoutSuccessUrl("/toLogin")
//                .logoutUrl("/logout")
//                .clearAuthentication(true)
//                .invalidateHttpSession(true)
//                .permitAll()
//                .and().csrf().disable();


    }
}
